<template>
  <div class="container">
    <header-search-form
      :searchFormData="searchForm"
      @search="search"
      @deleteSelectedDevice="deleteSelectedDevice"
    />
    <lan-table
      size="small"
      :config="dataTable"
      :tableData="tableData"
      @search="search"
      @selection-change="getDeviceUuidList"
    >
      <template #type="scope">
        <el-input v-model="scope.row.type"></el-input>
      </template>
    </lan-table>
    <el-dialog
      width="600px"
      title="地址"
      :visible.sync="addDialogVisible"
    >
      <el-table
        stripe
        :data="addressList"
      >
        <el-table-column
          prop="latitude"
          label="纬度"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="longitude"
          label="经度"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="location"
          label="地址"
          align="center"
        ></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      width="600px"
      title="数据列表"
      :visible.sync="dialogVisible"
    >
      <el-table
        stripe
        :data="showDeviceTableData"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="name"
          label="编号/名称"
        ></el-table-column>
        <el-table-column
          prop="display_name"
          label="中文名称"
        >
        </el-table-column>
        <el-table-column
          prop="value"
          label="数值"
        >
          <template slot-scope="scope">
            {{ scope.row.value.toString() }}
          </template>
        </el-table-column>
        <el-table-column
          prop="unit"
          label="计量单位"
        ></el-table-column>
      </el-table>
      <div class="receive-device-footer">
        <el-pagination
          background="#fff"
          @size-change="pageSizeChangeHandler"
          @current-change="currentPageChangeHandler"
          :current-page.sync="searchFormDialog.currentPage"
          :page-size.sync="searchFormDialog.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          layout="total,sizes, prev, pager, next, jumper"
          :total="searchFormDialog.totalCount"
          align="right"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import lanTable from '../../../components/lanTable';
import { deleteDeviceApi, getDeviceInfoApi } from '../../../api/device';
import moment from 'moment';
import { MomentFormat, SortType } from '../../../constants/common';
import { Message, MessageBox } from 'element-ui';
import { getDeviceListApi, deleteSelectedDeviceApi } from '../../../api/device';
import { parseError } from '../../../utils';
import { getDisplay, getStatusColor, getActiveDisplay, getActiveColor } from './service';
import HeaderSearchForm from './headerSearchForm.vue';

export default {
  name: 'DeviceList',
  components: {
    lanTable,
    HeaderSearchForm
  },
  data() {
    return {
      selectedDeviceUuidList: [],
      btnLoading: false,
      addDialogVisible: false,
      dialogVisible: false,
      deviceUuidList: [],

      address: {
        longitude: null,
        latitude: null,
        location: ''
      },
      addressList: [],

      searchForm: {
        btnLoading: false,
        typeUuid: '',
        factoryUuid: '',
        name: '',
        serialNumber: '',
        versionName: '',
        status: ''
      },

      active: true,
      tableData: [],
      dataTable: {
        pageSize: 10,
        totalCount: 0,
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        sort: {
          sortType: SortType.DESC,
          orderBy: 'createdAt'
        },
        columnList: [
          {
            type: 'selection',
            width: '50px',
            label: ''
          },
          {
            name: 'factoryName',
            label: '工厂名称'
          },
          {
            name: 'typeName',
            label: '类型名称'
          },
          {
            name: 'serialNumber',
            label: '序列号',
            sortable: true
          },
          {
            name: 'name',
            label: '设备名称',
            sortable: true
          },

          {
            label: '地址',
            type: 'button',
            name: 'uuid',
            scope: true,
            width: '100px',
            buttons: [
              {
                size: 'small',
                text: '查看',
                icon: 'el-icon-tickets',
                method: row => this.checkDetail(row.uuid)
              }
            ]
          },
          {
            label: '数据',
            type: 'button',
            name: 'dataList',
            scope: true,
            width: '100px',
            buttons: [
              {
                size: 'small',
                text: '查看',
                icon: 'el-icon-tickets',
                method: row => this.checkData(row)
              }
            ]
          },
          {
            label: '历史数据',
            type: 'button',
            scope: true,
            width: '100px',
            buttons: [
              {
                size: 'small',
                text: '查看',
                icon: 'el-icon-tickets',
                method: row => this.checkHistory(row.uuid, row.name, row.serialNumber)
              }
            ]
          },
          {
            label: '设备状态',
            type: 'formatter',
            name: 'status',
            scope: true,
            width: '100px',
            formatter: getDisplay,
            style: {
              color: getStatusColor
            }
          },
          {
            label: '是否可用',
            type: 'formatter',
            name: 'active',
            scope: true,
            width: '100px',
            formatter: getActiveDisplay,
            style: {
              color: getActiveColor
            }
          },
          {
            name: 'createdAt',
            label: '创建时间',
            sortable: true
          },
          {
            name: 'updatedAt',
            label: '更新时间',
            sortable: true
          },
          {
            type: 'button',
            label: '操作',
            buttons: [
              {
                isShow: () => this.userGuardList.includes(this.guard.DeviceManage),
                type: 'text',
                text: '编辑',
                size: 'small',
                method: row => {
                  this.showEdit(row.uuid);
                }
              },
              {
                isShow: () => this.userGuardList.includes(this.guard.DeviceManage),
                type: 'text',
                text: '删除',
                size: 'small',
                method: row => {
                  this.remove(row.uuid, row.name);
                }
              }
            ]
          }
        ]
      },
      searchFormDialog: {
        currentPage: 1,
        pageSize: 10,
        totalCount: 0
      },
      dataList: [],
      showDeviceTableData: []
    };
  },
  watch: {
    dataList: {
      handler(val) {
        this.searchFormDialog.totalCount = val.length;
      }
    }
  },
  created() {
    this.search();
  },
  methods: {
    searchDialog() {
      this.showDeviceTableData = this.dataList.slice(
        (this.searchFormDialog.currentPage - 1) * this.searchFormDialog.pageSize,
        this.searchFormDialog.currentPage * this.searchFormDialog.pageSize
      );
    },
    pageSizeChangeHandler() {
      this.searchFormDialog.currentPage = 1;
      this.searchDialog();
    },
    currentPageChangeHandler() {
      this.searchDialog();
    },
    getDeviceUuidList(value) {
      this.deviceUuidList = value.map(device => device.uuid);
    },
    deleteSelectedDevice() {
      if (this.deviceUuidList.length == 0) return Message.warning('请选择要删除的设备');
      MessageBox.confirm(`是否确认删除选中的设备`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        deleteSelectedDeviceApi(this.deviceUuidList)
          .then(res => Message.success(`成功删除${res.count}个设备`))
          .catch(error => Message.error(parseError(error)))
          .finally(this.search());
      });
    },
    order(value) {
      this.orderBy = value;
    },
    search() {
      this.searchForm.btnLoading = true;
      getDeviceListApi(
        this.dataTable.currentPage - 1,
        this.dataTable.pageSize,
        this.dataTable.sort.sortType,
        this.dataTable.sort.orderBy,
        this.searchForm.typeUuid,
        this.searchForm.factoryUuid,
        this.searchForm.name,
        this.searchForm.serialNumber,
        this.searchForm.status,
        this.searchForm.active
      )
        .then(({ total_count, data }) => {
          this.dataTable.totalCount = total_count;
          this.tableData = data.map(device => {
            return {
              uuid: device.uuid,
              typeName: device.type_name,
              typeUuid: device.type_uuid,
              factoryName: device.factory_name || null,
              factoryUuid: device.factory_uuid || null,
              name: device.name,
              serialNumber: device.serial_number,
              latitude: device.latitude,
              longitude: device.longitude,
              location: device.location,
              status: device.status,
              createdAt: moment(device.created_at).format(MomentFormat),
              updatedAt: moment(device.updated_at).format(MomentFormat),
              dataList: device.data_list || null,
              active: device.active
            };
          });
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.searchForm.btnLoading = false));
    },
    checkDetail(uuid) {
      this.addressList = [];
      this.btnLoading = true;
      getDeviceInfoApi(uuid)
        .then(res => {
          this.address.latitude = res.latitude;
          this.address.longitude = res.longitude;
          this.address.location = res.location;
          this.addressList.push(this.address);
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => {
          this.addDialogVisible = true;
          this.btnLoading = false;
        });
    },
    checkData(row) {
      this.dataList = row.dataList || [];
      this.searchDialog();
      this.$nextTick(() => {
        this.searchFormDialog.totalCount = this.dataList.length;
        this.searchDialog();
      });
      this.dialogVisible = true;
    },
    checkHistory(uuid, name, serialNumber) {
      let historyRoute = this.$router.resolve({
        name: 'deviceHistory',
        query: {
          uuid: uuid,
          name: name,
          sn: serialNumber
        }
      });
      window.open(historyRoute.href, '_blank');
    },
    remove(uuid, name) {
      MessageBox.confirm(`确定删除区域${name}吗？`, '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteDeviceApi(uuid)
            .then(() => Message.success('删除设备成功'))
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    },
    showEdit(uuid) {
      this.$router.push('/device/edit/' + uuid);
    }
  }
};
</script>

<style lang="scss">
.container {
  padding: 10px;
}
.receive-device-footer {
  padding-top: 10px;
}
</style>

